//
// Created by sgyt on 2020/2/4.
//
/**
 * fork之后父进程和子进程之间对打开文件的共享
 */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
int main(int argc,char *argv[])
{
    int fid,pid,readsize,i=0;
    char buf[3];
    memset(buf,0x00, sizeof(buf));
    fid = open("sgyt.txt",O_RDWR,O_CREAT);
    //write(fid,"sgytjwdwjwdjwwjdwjdwdjwj", sizeof("sgytjwdwjwdjwwjdwjdwdjwj"));
    readsize = read(fid,buf, sizeof(buf));
    printf("read = [%s],size = [%d]\n",buf,readsize);

    for(i=0;i<3;i++)
    {
        pid = fork();
        if(pid<0)//创建进程失败
        {
            exit(0);
        } else if (pid > 0)//父进程
        {
            if(i == 0)
            {
                printf("father create pid = [%d],fpid = [%d]\n",getpid(),getppid());
            }
            sleep(1);
        } else if (pid == 0)//子进程
        {
            printf("child create pid = [%d],fpid = [%d]\n",getpid(),getppid());
            break;
        }
    }

    if(i == 0)//1号子进程
    {
        printf("child finish pid = [%d],fpid = [%d]\n",getpid(),getppid());
        readsize = read(fid,buf, sizeof(buf));
        printf("read = [%s],size = [%d]\n",buf,readsize);
    } else if(i == 1)//2号子进程
    {
        printf("child finish pid = [%d],fpid = [%d]\n",getpid(),getppid());
        readsize = read(fid,buf, sizeof(buf));
        printf("read = [%s],size = [%d]\n",buf,readsize);
    } else if (i == 2)//3号子进程
    {
        printf("child finish pid = [%d],fpid = [%d]\n",getpid(),getppid());
        readsize = read(fid,buf, sizeof(buf));
        printf("read = [%s],size = [%d]\n",buf,readsize);
    }else if(i == 3)//父进程
    {
        printf("father finish pid = [%d],fpid = [%d]\n",getpid(),getppid());
        readsize = read(fid,buf, sizeof(buf));
        printf("read = [%s],size = [%d]\n",buf,readsize);
    }

    return 0;
}
